package com.yonyougov.devops.cruxcisupport.version;

import com.yonyougov.devops.cruxcisupport.app.AppService;
import com.yonyougov.devops.cruxcisupport.harbor.artifact.HarborArtifactService;
import com.yonyougov.devops.cruxcisupport.server.ServerEntity;
import com.yonyougov.devops.cruxcisupport.util.SshUtil;
import com.yonyougov.devops.cruxcisupport.version.dto.*;
import com.yonyougov.devops.cruxcisupport.version.util.VersionUrlInfo;
import com.yonyougov.devops.cruxcisupport.version.vo.VersionNameVo;
import com.yonyougov.devops.cruxcisupport.version.vo.VersionPageVo;
import com.yonyougov.devops.cruxcisupport.versioninfo.VersionInfoEntity;
import com.yonyougov.devops.cruxcisupport.versioninfo.VersionInfoService;
import com.yonyougov.devops.cruxcisupport.versioninfo.dto.RelationVersionInfoAddDto;
import com.yonyougov.devops.fwc.api.dto.BaseResponseDto;
import com.yonyougov.devops.fwc.core.controller.CrudController;
import com.yonyougov.devops.fwc.core.service.BaseService;
import io.micrometer.core.instrument.util.StringUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.math.BigInteger;
import java.sql.SQLOutput;
import java.util.List;
import java.util.Locale;

/**
 * Created by ligson on 2017/8/11.
 */
@RestController
@RequestMapping("/api/v2/version")
public class VersionController extends CrudController<VersionEntity, BigInteger> {
    @Autowired
    private VersionUrlInfo versionUrlInfo;

    @Autowired
    private HarborArtifactService harborArtifactService;
    private final VersionInfoService versionInfoService;
    private final VersionService versionService;
    private final AppService appService;

    public VersionController(VersionInfoService versionInfoService, VersionService versionService, AppService appService) {
        this.versionInfoService = versionInfoService;
        this.versionService = versionService;
        this.appService = appService;
    }

    @Override
    public BaseService<VersionEntity, BigInteger> getService() {
        return versionService;
    }

    @ApiOperation(value = "前端应用模块-新增应用版本调用", notes = "增加应用版本")
    @PostMapping(value = "/v/add")
    public BaseResponseDto addVersion(@RequestBody @Valid VersionAddRequestDto requestDto) {
        VersionEntity versionEntity = new VersionEntity();

        VersionInfoEntity versionInfoEntity = new VersionInfoEntity();

        requestDto.setDevelopVersion(requestDto.getVersionName().toUpperCase().endsWith("SNAPSHOT")?true:false);
        BeanUtils.copyProperties(requestDto, versionEntity,new String[]{"versionType","versionDesc"});

        versionService.add(versionEntity);

        versionInfoEntity.setVersionId(versionService.findBy(versionEntity).getId());
        versionInfoEntity.setCreateTime(versionService.findBy(versionEntity).getCreateTime());

        //判断版本信息是否有
        if( !versionEntity.getDevelopVersion() && requestDto.getVersionDesc()!=null){
            versionInfoEntity.setVersionDesc(requestDto.getVersionDesc());
            versionInfoEntity.setType(requestDto.getVersionType());
            versionInfoService.add(versionInfoEntity);
        }
        return BaseResponseDto.getSuccessInstance();
    }
    //<!--用户自定义代码结束-->

    @ApiOperation(value = "前端应用模块-修改应用版本调用", notes = "修改应用版本")
    @PostMapping(value = "/v/update")
    public BaseResponseDto updateVersion(@RequestBody @Valid VersionUpdateRequestDto requestDto) {
        VersionEntity versionEntity = new VersionEntity();
        requestDto.setDevelopVersion(requestDto.getVersionName().toUpperCase().endsWith("SNAPSHOT")?true:false);
        VersionInfoEntity versionInfoEntity = new VersionInfoEntity();
        versionInfoEntity.setType(requestDto.getVersionType());
        versionInfoEntity.setVersionDesc(requestDto.getVersionDesc());

        BeanUtils.copyProperties(requestDto, versionEntity,new String[]{"versionType","versionDesc"});

        versionService.update(versionEntity);

        if( !versionEntity.getDevelopVersion() && requestDto.getVersionDesc()!=null){

            versionInfoEntity.setVersionId(versionService.findBy(versionEntity).getId());
            versionInfoEntity.setCreateTime(versionService.findBy(versionEntity).getCreateTime());
            versionInfoEntity.setId(versionInfoService.findBy(versionInfoEntity).getId());
            versionInfoService.update(versionInfoEntity);
        }

        return BaseResponseDto.getSuccessInstance();
    }

    @ApiOperation(value = "前端版本列表调用", notes = "根据应用id分页查版本")
    @PostMapping(value = "/v/page")
    public VersionPageVo findVersionPage(@RequestBody FindVersionByAppIdRequestDto requestDto) {
        VersionEntity versionEntity = new VersionEntity();
        BeanUtils.copyProperties(requestDto, versionEntity);

        return versionService.findPageByAppId(versionEntity);
    }

//    @ApiOperation(value = "前端部署模块-更改版本调用", notes = "根据应用id查版本")
//    @PostMapping(value = "/v/names")
//    public BaseResponseDto getAllVersionNamByAppId(@RequestBody FindVersionByAppIdRequestDto requestDto) {
//        VersionEntity versionEntity = new VersionEntity();
//        BeanUtils.copyProperties(requestDto, versionEntity);
//        versionEntity.setPageAble(false);
//
//        List<VersionNameVo> versionNameVoList = versionService.findVersionByAppId(versionEntity);
//
//        BaseResponseDto baseResponseDto = BaseResponseDto.getSuccessInstance();
//        baseResponseDto.getData().put("names", versionNameVoList);
//        return baseResponseDto;
//    }

    @ApiOperation(value = "前端部署模块-更改版本调用", notes = "根据应用id和状态status查版本")
    @PostMapping(value = "/v/names")
    public BaseResponseDto getAllVersionNamByAppIdAndStatus(@RequestBody FindVersionByAppIdRequestDto requestDto) {
        VersionEntity versionEntity = new VersionEntity();
        BeanUtils.copyProperties(requestDto, versionEntity);
        versionEntity.setPageAble(false);

        List<VersionNameVo> versionNameVoList = versionService.findVersionByAppIdAndStatus(versionEntity);

        BaseResponseDto baseResponseDto = BaseResponseDto.getSuccessInstance();
        baseResponseDto.getData().put("names", versionNameVoList);
        return baseResponseDto;
    }

    @ApiOperation(value = "删除应用版本", notes = "删除应用版本")
    @PostMapping(value = "/v/delete/id")
    public BaseResponseDto deleteVersionById(@RequestBody @Valid DeleteVersionRequestDto requestDto) {
        VersionEntity versionEntity = new VersionEntity();
        versionEntity.setId(requestDto.getId());

        versionService.deleteCascadeByPrimaryKey(versionEntity);

        return BaseResponseDto.getSuccessInstance();
    }
    @ApiOperation(value = "查看下载地址", notes = "查看下载地址")
    @PostMapping(value = "/v/set/url")
    public String setUrlbyAppAndversion(@RequestBody @Valid FindVersionByAppIdRequestDto requestDto) {
        VersionEntity versionEntity = new VersionEntity();
        versionEntity.setAppId(requestDto.getAppId());
        versionEntity.setVersionName(requestDto.getVersionName());
        versionEntity.setId(requestDto.getId());
        return versionService.findUrlByAppAndVersion(versionEntity);
    }


    @ApiOperation(value = "生成下载地址", notes = "生成下载地址")
    @PostMapping(value = "/v/create/url")
    public String createUrlbyAppAndversion(@RequestBody @Valid FindVersionByAppIdRequestDto requestDto) {
        VersionEntity versionEntity = new VersionEntity();
        versionEntity.setAppId(requestDto.getAppId());
        versionEntity.setId(requestDto.getId());
        String app = appService.get(versionEntity.getAppId()).getApp();
        versionEntity.setVersionName(requestDto.getVersionName());
        //读取连接服务器
        SshUtil sshUtil = new SshUtil();
        ServerEntity server = new ServerEntity();
        server.setIp(versionUrlInfo.getIp());
        server.setPort(versionUrlInfo.getPost());
        server.setUsername(versionUrlInfo.getUser());
        server.setConnectType(1);
        //判断镜像版本是否存在
            if(harborArtifactService.findAppVersionfromHaber(app,versionEntity.getVersionName())){
                String result = sshUtil.exeCmd(server, versionUrlInfo.getSh()+ " "+ app+ " "+ versionEntity.getVersionName());
                if(result.isEmpty()){
                    return "服务器无法连接";
                }
                versionEntity.setUrl(versionUrlInfo.getUrl()+"/"+app+"/"+app+"-"+versionEntity.getVersionName()+"-tar");
                versionEntity.setVersionName(null);
                versionEntity.setAppId(null);
                versionService.update(versionEntity);
                return "地址已生成";
            }
            return "版本信息不存在";
    }
}
